//
//  HESecurityViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2021/2/23.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HESecurityViewController.h"
#import "HESettingSwitchCell.h"
#import "HEGesturesPWDViewController.h"
#import "HESecurtyChainData.h"
#import "HETouchID.h"

@interface HESecurityViewController ()<UITableViewDelegate, UITableViewDataSource, HESettingSwitchCellDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *notices;

@end

@implementation HESecurityViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"账户与安全";
    
    [self.view addSubview:self.tableView];
    
    [self initCell];
}

- (void)initCell {

    _sections = [NSMutableArray array];
    NSMutableArray *classArr = [NSMutableArray array];
    
    
    BOOL isSave = [HESecurtyChainData isSave]; //是否有保存
    self.formModel.st_openGestures = [NSNumber numberWithBool:isSave];
    
    [self getHasFingerprintPWD];

    // switchcell
    GDFiterCellModel *gestureModel = [GDFiterCellModel new];
    gestureModel.cellKlass = HESettingSwitchCell.class;
    gestureModel.leftTitle = @"手势密码";
    gestureModel.cellType = GDFiterCellTypeSettingGesturePWD;
    gestureModel.tableKey = @"st_openGestures";
    [classArr addObject: gestureModel];

    if ([[HETouchID sharedInstance] td_canSupperBiometrics] == HETouchIDSupperTypeTouchID) {
        
        GDFiterCellModel *fingerprintModel = [GDFiterCellModel new];
        fingerprintModel.cellKlass = HESettingSwitchCell.class;
        fingerprintModel.leftTitle = @"指纹登录";
        fingerprintModel.cellType = GDFiterCellTypeSettingFingerprintPWD;
        fingerprintModel.tableKey = @"st_openFingerprint";
        [classArr addObject: fingerprintModel];
    }else if ([[HETouchID sharedInstance] td_canSupperBiometrics] == HETouchIDSupperTypeFaceID) {
        GDFiterCellModel *fingerprintModel = [GDFiterCellModel new];
        fingerprintModel.cellKlass = HESettingSwitchCell.class;
        fingerprintModel.leftTitle = @"面容登录";
        fingerprintModel.cellType = GDFiterCellTypeSettingFingerprintPWD;
        fingerprintModel.tableKey = @"st_openFingerprint";
        [classArr addObject: fingerprintModel];
    }
     
    [self.tableView mc_registerCellByFiterModels:classArr];
    
    for (GDFiterCellModel *model in classArr) {
        NSMutableArray *sec = [NSMutableArray array];
        [sec addObject:model];
        [_sections addObject:sec];
    }
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight) style:UITableViewStyleGrouped];
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 20)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (NSMutableArray *)notices {
    if (!_notices) {
        _notices = @[@"开启后可使用手势密码快速完成登录，手势密码仅对本手机有效", ].mutableCopy;
        
        if ([[HETouchID sharedInstance] td_canSupperBiometrics] == HETouchIDSupperTypeTouchID) {
            [_notices addObject:@"开启后可使用指纹验证快速完成登录，指纹登录仅对本手机有效"];
        }else if ([[HETouchID sharedInstance] td_canSupperBiometrics] == HETouchIDSupperTypeFaceID) {
            [_notices addObject:@"开启后可使用面容验证快速完成登录，面容登录仅对本手机有效"];
        }
    }
    return _notices;
}


#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    return 55;

//    return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
//               [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
//    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    
    UILabel *noticLb = [UILabel new];
    noticLb.numberOfLines = 0;
    noticLb.textColor = CNavSubTitleColor;
    noticLb.font = DYFont(15);
    noticLb.text = self.notices[section];
    [view addSubview:noticLb];
    
    [noticLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view).offset(10);
        make.left.equalTo(view).offset(10);
        make.right.equalTo(view).offset(-10);
        make.bottom.equalTo(view).offset(-10);
    }];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 60;
}

#pragma mark - HESettingSwitchCellDelegate
- (void)switchChange:(HESettingSwitchCell *)cell {
    switch (cell.fiterModel.cellType) {
        case GDFiterCellTypeSettingGesturePWD:
        {
            BOOL isSave = [self getHasGesturePWD];
            
            if (isSave) {
                [HESecurtyChainData forgotPsw];
                [self getHasGesturePWD];
                [Dialog toastBottom:@"已关闭手势密码验证"];
            }else {
                HEGesturesPWDViewController *vc = [HEGesturesPWDViewController new];
                vc.gestureModel = isSave ? HEGesturesPasswordModelDelete : HEGesturesPasswordModelReset;
                KWeakSelf
                vc.backBlock = ^() {
                    [weakSelf getHasGesturePWD];
                };
                [self.navigationController pushViewController:vc animated:YES];
            }
        }
            break;
        case GDFiterCellTypeSettingFingerprintPWD:
        {
            BOOL isSave = [self getHasFingerprintPWD];
            
            [[HETouchID sharedInstance] td_showTouchIDWithDescribe:nil  BlockState:^(HETouchIDState state, NSError *error) {
                if (state == HETouchIDStateSuccess) {    //TouchID/FaceID验证成功
                    if (isSave) {
                        [HESecurtyChainData removeFingerprintPWD];
                        [Dialog toastBottom: [NSString stringWithFormat:@"已关闭%@", cell.fiterModel.leftTitle]];
                    }else {
                        [HESecurtyChainData saveFingerprintPWD];
                        [Dialog toastBottom: [NSString stringWithFormat:@"已开启%@", cell.fiterModel.leftTitle]];
                    }
                    [self getHasFingerprintPWD];
                }
                
//                if (state == HETouchIDStateInputPassword) {
//                    DLog(@"切换登录方式")
//                }
                
                // ps:以上的状态处理并没有写完全!
                // 在使用中你需要根据回调的状态进行处理,需要处理什么就处理什么
            }];
        }
            break;
        default:
            break;
    }
}

- (BOOL)getHasGesturePWD {
    BOOL isSave = [HESecurtyChainData isSave]; //是否有保存
    self.formModel.st_openGestures = [NSNumber numberWithBool:isSave];
    [self.tableView reloadData];
    return isSave;
}

- (BOOL)getHasFingerprintPWD {
    BOOL isSave = [HESecurtyChainData hasFingerprint]; //是否有保存
    self.formModel.st_openFingerprint = [NSNumber numberWithBool:isSave];
    [self.tableView reloadData];
    return isSave;
}

@end
